package com.wanglibao.woodtrade.woodtrade.ui.fragment;


import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.entity.MyCSOrderDetails;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;
import com.wanglibao.woodtrade.woodtrade.model.impl.UserImpl;
import com.wanglibao.woodtrade.woodtrade.ui.activity.adapter.ItemLvMyOrderActivityAdapter;
import com.wanglibao.woodtrade.woodtrade.util.PullUtil;
import com.wanglibao.woodtrade.woodtrade.util.ToastUtil;
import com.wanglibao.woodtrade.woodtrade.widget.PullToRefreshView.PullToRefreshBase;
import com.wanglibao.woodtrade.woodtrade.widget.PullToRefreshView.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
@SuppressLint("ValidFragment")
public class MyCSOrderFragment extends BaseFragment implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2 {

    ItemLvMyOrderActivityAdapter mAdapter;
    List<String> mList = new ArrayList<>();
    @Bind(R.id.lv_my_order_chushou_fragment)
    PullToRefreshListView mLvMyOrderChushouFragment;
    //=======================================
    Timer mTimer = new Timer();
    long begin = System.currentTimeMillis();
    Gson gson = new Gson();
    MyCSOrderDetails myCSOrderDetails;
    long total;
    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.arg2 == 20) {
                for (int i = 0; i < myCSOrderDetails.getOrder_list().size(); i++) {
                    if (myCSOrderDetails.getOrder_list().get(i).getOrder_status().equals("0")) {
                         total = Long.parseLong(myCSOrderDetails.getOrder_list().get(i).getC_time());
                    } else if(myCSOrderDetails.getOrder_list().get(i).getOrder_status().equals("1")) {
                         total = Long.parseLong(myCSOrderDetails.getOrder_list().get(i).getPay_time());
                    }
                    long now = System.currentTimeMillis();
                    long pdata = total * 1000 + 3600 * 24 * 1000;
                    long pdata1 = total * 1000 + 3600 * 72 * 1000;
                    long left = pdata - now;
                    long left1 = pdata1 - now;
                    TextView textView = getTVInPostion(i);
                    if (textView != null) {
                        if(myCSOrderDetails.getOrder_list().get(i).getOrder_status().equals("2")) {
                            textView.setText("");
                        }else {
                            if (myCSOrderDetails.getOrder_list().get(i).getDelay().equals("0")) {

                                if(left>0){
                                    textView.setText(convertTimeFormat(left));
                                }else {
                                    textView.setText("");
                                }
                            } else {
                                if(left1>0){
                                    textView.setText(convertTimeFormat(left1));
                                }else {
                                    textView.setText("");
                                }

                            }
                        }


                    }
                }
            } else {
                System.out.println(msg.obj.toString());
                if (msg.arg2 == 2) {
                    if (pagrNumber == 1) {
                        if (myCSOrderDetails != null) {
                            myCSOrderDetails.getOrder_list().clear();
                        }
                        mAdapter.setList(myCSOrderDetails.getOrder_list());
                    } else {
                        ToastUtil.createLongToast(getContext(), "没有更多数据了");
                        pagrNumber--;
                    }
                } else {
                    MyCSOrderDetails myCSOrderDetails1 = new Gson().fromJson(msg.obj.toString(), MyCSOrderDetails.class);
                    if (pagrNumber == 1) {
                        myCSOrderDetails = myCSOrderDetails1;
                    } else {
                        myCSOrderDetails.getOrder_list().addAll(myCSOrderDetails1.getOrder_list());
                    }
                    mAdapter.setList(myCSOrderDetails.getOrder_list());
                    mTimer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            Message message = mHandler.obtainMessage();
                            message.arg2 = 20;
                            mHandler.sendMessage(message);

                        }
                    }, 0, 1000);
                }
            }

            if(mLvMyOrderChushouFragment!=null){
                mLvMyOrderChushouFragment.onRefreshComplete();
            }
            return false;
        }
    });
    public int zhuangtai = 4;

    public MyCSOrderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_csorder, container, false);
        ButterKnife.bind(this, view);
        initView();
        isPreview = false;
        return view;
    }

    public TextView getTVInPostion(int positon) {
        for (TextView textView : mAdapter.mTextViews_left_time) {
            if ((Integer) textView.getTag() == positon) {
                return textView;
            }
        }
        return null;
    }

    //把毫秒值转换成时.分.秒格式
    public String convertTimeFormat(long timeAll) {
        int day = (int) (timeAll / (1000 * 60 * 60 * 24));
        int timeleft0 = (int) (timeAll % (1000 * 60 * 60 * 24));
        int hour = timeleft0 / (1000 * 60 * 60);
        int timeleft1 = (int) (timeAll % (1000 * 60 * 60));
        int minute = timeleft1 / (1000 * 60);
        int timeleft2 = (int) (timeAll % (1000 * 60));
        int second = timeleft2 / 1000;
        if (day > 0) {
            return "剩余时间：" + day + "天" + hour + "时" + minute + "分" + second + "秒";
        } else {
            return "剩余时间：" + hour + "时" + minute + "分" + second + "秒";
        }

    }

    boolean isPreview = false;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint() && isVisible()) {
            NetWorking(4);
            isPreview = true;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isPreview) {
            NetWorking(4);
        }

    }

    private void initView() {
        //通用 初始化
        myCSOrderDetails = new MyCSOrderDetails();
        myCSOrderDetails.setOrder_list(new ArrayList<MyCSOrderDetails.OrderListBean>());
        mAdapter = new ItemLvMyOrderActivityAdapter(getContext(), myCSOrderDetails.getOrder_list(), this);
        mLvMyOrderChushouFragment.getRefreshableView().setAdapter(mAdapter);
        mLvMyOrderChushouFragment.getRefreshableView().setOnItemClickListener(this);
        mLvMyOrderChushouFragment.setMode(PullToRefreshBase.Mode.BOTH);
        mLvMyOrderChushouFragment.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
        mLvMyOrderChushouFragment.setOnRefreshListener(this);
        PullUtil.initIndicator(mLvMyOrderChushouFragment);
    }

    public void NetWorking(int status) {
        zhuangtai = status;
        //SERVER_wangliwei
        JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(false, this, NetConfig.SERVER + NetConfig.TYPE_ORDER,
                NetConfig.order_list, mHandler,
                "jsonObject", NetConfig.TaskId.order_list,
                new Object[]{pagrNumber, zhuangtai, new UserImpl(getContext()).getUser().token, 1});
        jsonRPCAsyncTask.execute(new Void[]{});
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public int pagrNumber = 1;

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    // 下拉
    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        pagrNumber = 1;
        NetWorking(zhuangtai);
    }

    //上推
    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        pagrNumber++;
        NetWorking(zhuangtai);
    }
}
